package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.article.ArticleConstants;
import com.heima.model.common.constants.message.NewsUpOrDownConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import io.seata.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;
    @Autowired
    AuthorMapper authorMapper;
    @Autowired
    AdminFeign adminFeign;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Value("${file.oss.web-site}")
    private String webSite;

    @Value("${file.minio.readPath}")
    String readPath;
    @Autowired
    GeneratePageService generatePageService;

    @Transactional
    @Override
    public void publishArticle(Integer newsId) {
        //1.查询并校验文章
        WmNews wmNews = getWmNews(newsId);
        //2。封装apArticle
        ApArticle apArticle = getApArticle(wmNews);
        //3。保存或修改文章
        saveOrUpdateArticle(apArticle);
        //4。保存关联文章配置
        saveConfigAndContent(wmNews, apArticle);
        //5。TODO 页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(), apArticle);
        //6。更新wmNews状态 改为9  并设置articleId
        updateWmNews(wmNews, apArticle);
        //7。TODO 通知es索引库添加文章索引

        rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE,apArticle.getId());
        log.info("文章发布成功，并发送索引库更新通知   文章id: {}",apArticle.getId());
    }




    /**
     * 根据参数加载文章列表
     *
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        //1 参数检查
        // 页大小
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = 10;
        }
        dto.setSize(size);
        // 频道
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);//全部
        }
        // 时间
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        // 类型判断
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE)
                && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;//默认查询更多
        }
        //2 调用articleMapper
        List<ApArticle> articleList = apArticleMapper.loadArticleList(dto, loadtype);
        for (ApArticle apArticle : articleList) {
            apArticle.setStaticUrl(readPath + apArticle.getStaticUrl());
        }


        //3 返回结果
        ResponseResult result = ResponseResult.okResult(articleList);
        result.setHost(webSite);
        return result;
    }

    /**
     * 根据参数加载文章列表
     *
     * @param loadtype  0为加载更多  1为加载最新
     * @param dto
     * @param firstPage 是否为首页 true 首页
     * @return
     */
    @Override
    public ResponseResult load2(Short loadtype, ArticleHomeDTO dto, boolean firstPage) {
        if (firstPage) {
            //redis
            String articleListJson = redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(articleListJson)) {
                List<ApArticle> apArticles = JSON.parseArray(articleListJson, ApArticle.class);
                for (ApArticle apArticle : apArticles) {
                    apArticle.setStaticUrl(readPath + apArticle.getStaticUrl());
                }
                ResponseResult result = ResponseResult.okResult(apArticles);
                result.setHost(webSite);
                return result;
            }
        }


        return load(loadtype, dto);
    }

    /**
     * 更新wmNews状态
     *
     * @param wmNews
     * @param apArticle
     */
    private void updateWmNews(WmNews wmNews, ApArticle apArticle) {
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());//常量
        wmNews.setArticleId(apArticle.getId());
        ResponseResult updateResult = wemediaFeign.updateWmNews(wmNews);
        if (!updateResult.checkCode()) {
            log.error("文章发布失败  远程调用修改文章接口失败，   不予发布，文章id：{}", wmNews.getId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用修改文章接口失败");//504远程调用出错
        }
    }

    /**
     * 保存关联文章配置
     *
     * @param wmNews
     * @param apArticle
     */
    private void saveConfigAndContent(WmNews wmNews, ApArticle apArticle) {
        //1。保存配置信息
        ApArticleConfig config = new ApArticleConfig();
        config.setArticleId(apArticle.getId());//文章id
        config.setIsForward(true);//是否转发
        config.setIsComment(true);//是否评论
        config.setIsDown(false);//是否下架
        config.setIsDelete(false);//是否·删除
        apArticleConfigMapper.insert(config);

        //  添加文章详情
        ApArticleContent content = new ApArticleContent();
        content.setArticleId(apArticle.getId());
        content.setContent(wmNews.getContent());//内容

    }

    /**
     * 保存或修改文章
     *
     * @param apArticle
     */

    private void saveOrUpdateArticle(ApArticle apArticle) {
        // 判断wmNews之前是否关联 articleId
        if (apArticle.getId() == null) {
            // 无关联  新增 article
            // 保存文章
            apArticle.setCollection(0); // 收藏数
            apArticle.setLikes(0);// 点赞数
            apArticle.setComment(0);// 评论数
            apArticle.setViews(0); // 阅读数
            save(apArticle);
        } else {
            // 有关联  修改 article
            // 修改文章  删除之前关联的配置信息   内容信息
            ApArticle article = getById(apArticle.getId());
            if (article == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "关联的文章不存在");
            }
            updateById(apArticle);
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, apArticle.getId()));
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId()));
        }
    }

    /**
     * 封装apArticle
     *
     * @param wmNews
     * @return
     */


    private ApArticle getApArticle(WmNews wmNews) {

        ApArticle apArticle = new ApArticle();
        // 拷贝属性
        BeanUtils.copyProperties(wmNews, apArticle);
        apArticle.setId(wmNews.getArticleId());
        apArticle.setFlag((byte) 0); // 普通文章
        apArticle.setLayout(wmNews.getType());// 布局
        // 远程查询频道信息
        ResponseResult<AdChannel> channelResult = adminFeign.findOne(wmNews.getChannelId());
        if (!channelResult.checkCode()) {
            log.error("文章发布失败 远程调用查询频道出现异常， 不予发布 , 文章id : {}  频道id : {}", wmNews.getId(), wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用查询频道出现异常");
        }
        AdChannel channel = channelResult.getData();
        if (channel == null) {
            log.error("文章发布失败 未查询到相关频道信息， 不予发布 , 文章id : {}  频道id : {}", wmNews.getId(), wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "未查询到相关频道信息");
        }
        apArticle.setChannelName(channel.getName());
        // 设置作者信息
        ApAuthor author = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        if (author == null) {
            log.error("文章发布失败 未查询到相关作者信息， 不予发布 , 文章id : {}  自媒体用户id : {}", wmNews.getId(), wmNews.getUserId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "根据自媒体用户，查询关联作者信息失败");
        }
        apArticle.setAuthorId(Long.valueOf(author.getId()));
        apArticle.setAuthorName(author.getName());
        return apArticle;
    }


    /**
     * 远程查询并校验
     *
     * @param newsId
     * @return
     */
    private WmNews getWmNews(Integer newsId) {
        //1。使用feign查询自媒体文章
        ResponseResult<WmNews> wmNewsById = wemediaFeign.findWmNewsById(newsId);
        if (!wmNewsById.checkCode()) {
            log.error("远程查询自媒体文章信息失败  文章id：{}", newsId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用自媒体文章接口失败");//504
        }
        ;

        //2。校验文章是否存在
        WmNews wmNews = wmNewsById.getData();
        if (wmNews == null) {
            log.error("远程查询自媒体文章信息失败  文章id：{}", newsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章本身不存在");
        }


        //3。检验文章状态，是否为4，8
        short status = wmNews.getStatus().shortValue();
        if (WmNews.Status.ADMIN_SUCCESS.getCode() == status && WmNews.Status.SUCCESS.getCode() == status) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章状态不是审核状态，发布文章状态");
        }
        return wmNews;

    }
}